//
//  ZCameraPhotoEdit.m
//  danpin
//
//  Created by chuangjia on 5/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "ZCameraPhotoEdit.h"
#import "ZAssetsLibrary.h"
#import "FliterList.h"
#import "viewconfig.h"
@interface ZCameraPhotoEdit ()<FliterListDataSource,FliterListDelegate>
{
    
}

@property (weak) id<ZCameraDelegate> delegate;
@property (strong, nonatomic) UIImage *photo;
@property (strong, nonatomic) UIView *bottomView;
@property (assign, nonatomic) int  type;
//@property (nonatomic,strong)  FilterImageView *filterView;
@property (assign, nonatomic) BOOL  needSave;
@property(nonatomic,strong)FliterList *selectionList;
@property(nonatomic,strong)NSArray *fiterTitle;
@property(nonatomic,strong)NSArray *fiterImage;
@property(nonatomic,strong)NSArray *fiterName;
@property(nonatomic,strong) UIImageView *imageView;
+ (instancetype)newController;
@end

@implementation ZCameraPhotoEdit
@synthesize imageView=_imageView;

+ (instancetype)newController
{
    return [super new];
}

+ (instancetype)newWithDelegate:(id<ZCameraDelegate>)delegate photo:(UIImage *)photo type:(int)type
{
    ZCameraPhotoEdit *viewController = [ZCameraPhotoEdit newController];
    
    if (viewController) {
        viewController.needSave=NO;
        viewController.delegate = delegate;
        viewController.photo = photo;
        viewController.type =type;
    }
    return viewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.view.backgroundColor=CameraRGB(0x1e1e1e);
    
//    if (_filterView) {
//        [_filterView clean];
//        [_filterView removeFromSuperview];
//        _filterView=nil;
//    }
//    _filterView =[[FilterImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width) image:_photo];
//    _filterView.backgroundColor=[UIColor clearColor];
    
    if (_imageView) {
        [_imageView removeFromSuperview];
        _imageView=nil;
    }
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
    _imageView.image = _photo;
    
    [self.view addSubview:_imageView];

    _needSave =NO;
    self.fiterTitle = @[@"原图",@"冷调",@"胶片",@"优雅",@"Lomo",@"怀旧",@"摩登",@"复古",@"黑白"];
    self.fiterImage = @[@"f01.png",@"f04.png",@"f05.png",@"f06.png",@"f07.png",@"f08.png",@"f09.png",@"f10.png",@"f11.png"];
    self.fiterName =@[@"Original",@"CILinearToSRGBToneCurve",@"CIPhotoEffectChrome",@"CIFalseColor",@"CISepiaTone",@"CIPhotoEffectTransfer",@"CIColorMonochrome", @"CIPhotoEffectInstant",@"CIPhotoEffectMono"];
    
    
  
    [self initfilterView];
    [self.view addSubview:self.bottomView];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
      NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc{
    [self.bottomView removeFromSuperview];
    self.bottomView=nil;
//    if (self.filterView) {
//        [self.filterView clean];
//        [self.filterView removeFromSuperview];
//        self.filterView=nil;
//    }
    if (_imageView) {
        [_imageView removeFromSuperview];
        _imageView=nil;
    }
    if (self.selectionList) {
        self.selectionList.dataSource=nil;
        self.selectionList.delegate=nil;
        [self.selectionList removeFromSuperview];
        self.selectionList=nil;
    }
    NSLog(@"%s---", __PRETTY_FUNCTION__);
}

-(UIView*)bottomView
{
    if (!_bottomView) {
        self.bottomView =[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-50, self.view.frame.size.width, 50)];
        self.bottomView.backgroundColor = CameraRGB(0x1e1e1e);
        //
        //底部工具兰
        UIView *toolBarView =[[UIView alloc] initWithFrame:CGRectMake(0,  0, self.bottomView.frame.size.width,50)];
        toolBarView.backgroundColor=CameraRGB(0x1e1e1e);
        //
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.tag=10;
        UIImage *backImage = [UIImage imageNamed:@"back1.png"];
        [backBtn setImage: backImage forState:UIControlStateNormal];
         [backBtn setBackgroundImage: [UIImage imageNamed:@"back_press.png"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [backBtn setFrame:CGRectMake(0, 0, 50, 50)];
        [toolBarView addSubview:backBtn];
        //
       
        //
        UIButton *deviceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deviceBtn.tag =11;
        [deviceBtn setBackgroundImage: [UIImage imageNamed:@"ok.png"] forState:UIControlStateNormal];
        [deviceBtn setBackgroundImage: [UIImage imageNamed:@"ok_press.png"] forState:UIControlStateNormal];
        [deviceBtn addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [deviceBtn setFrame:CGRectMake(self.bottomView.frame.size.width-50, 0,50, 50)];
        [toolBarView addSubview:deviceBtn];
        [self.bottomView addSubview:toolBarView];
        toolBarView=nil;
    }
    return _bottomView;
}
-(void)toolButtonPressed:(id)sender
{
    UIButton *btn =(UIButton *)sender;
    switch (btn.tag) {
       
        case 10:
        {

            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
    
        case 11:
        {
//            UIImage *images =self.filterView.filterImage;
            UIImage *images =self.imageView.image;
            ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
            if (status == ALAuthorizationStatusAuthorized && (_needSave || self.type==0)) {
                ZAssetsLibrary *library = [ZAssetsLibrary defaultAssetsLibrary];
                [library saveImage:images completion:nil];
            }
            if ([_delegate respondsToSelector:@selector(cameraDidTakePhoto:)]) {
                [_delegate cameraDidTakePhoto:images];
            }
        }
            break;
            
        default:
            break;
    }
}

-(void)initfilterView
{
    if (self.selectionList) {
        self.selectionList.dataSource=nil;
        self.selectionList.delegate=nil;
        [self.selectionList removeFromSuperview];
        self.selectionList=nil;
    }
    _selectionList = [[FliterList alloc] initWithFrame:CGRectMake(0, self.view.frame.size.width, self.view.frame.size.width, 125)];
    _selectionList.delegate = self;
    _selectionList.dataSource = self;
    _selectionList.selectionIndicatorColor=UIColorFromRGB(0xd21d1d);
    _selectionList.bottomTrimColor =UIColorFromRGB(0xc7c8c8);
    [self.view addSubview:_selectionList];
    [_selectionList setSelectedButtonIndex:0];
    [_selectionList reloadData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 100;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
   
}
#pragma mark - HTHorizontalSelectionListDataSource Protocol Methods

- (NSInteger)numberOfItemsInSelectionList:(FliterList *)selectionList {
    return self.fiterTitle.count;
}

- (NSString *)selectionList:(FliterList *)selectionList titleForItemWithIndex:(NSInteger)index {
    NSString *kstr =[self.fiterTitle objectAtIndex:index];
    return kstr;
}
- (NSString *)selectionList:(FliterList *)selectionList imageNameForItemWithIndex:(NSInteger)index
{
    NSString *kstr =[self.fiterImage objectAtIndex:index];
    return kstr;
}
#pragma mark - HTHorizontalSelectionListDelegate Protocol Methods

- (void)selectionList:(FliterList *)selectionList didSelectButtonWithIndex:(NSInteger)index {
    if(index==0)
    {
        _needSave=NO;
    }else
    {
       _needSave =YES;
    }
//    [self.filterView switchFilter:(int)index];
   
    if (index>=self.fiterName.count) {
        return;
    }
    if(index==0)
    {
        self.imageView.image =self.photo;
    }else{
         self.imageView.image = [self filterImage:self.photo filtername:self.fiterName[index]];
    }
   
    
    
}
-(UIImage*)filterImage:(UIImage*)image filtername:(NSString *)name
{
    UIImage *filterimage = image;
    CIImage *ciImage = [[CIImage alloc] initWithImage:image];
    
    CIFilter *filter = [CIFilter filterWithName:name keysAndValues:kCIInputImageKey, ciImage, nil];
    [filter setDefaults];
    
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *outputImage = [filter outputImage];
    CGImageRef cgImage = [context createCGImage:outputImage fromRect:[outputImage extent]];
    filterimage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return filterimage;
}
@end
